package com.yedou.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.yedou.common.PageRequest;
import com.yedou.common.PageResult;
import com.yedou.common.Result;
import com.yedou.entity.po.User;
import com.yedou.service.UserService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
@RequestMapping("/users")
@Slf4j
public class UserController {

    @Autowired
    private UserService userService;

    // 分页查询用户
    @GetMapping("/page")
    public Result<PageResult<User>> pageUser(PageRequest pageRequest) {
        PageResult<User> pageResult = userService.pageUser
        (pageRequest.getPageNum(), pageRequest.getPageSize());
        return Result.pageSuccess(pageResult);
    }

    // 1. 查询所有用户
    @GetMapping
    public Result<List<User>> getAllUsers() {
        return Result.ok(userService.list()); // Service层提供的查询方法
    }

    // 2. 根据ID查询
    @GetMapping("/{id}")
    public Result<User> getUserById(@PathVariable Long id) {
        return Result.ok(userService.getById(id));
    }

    // 3. 添加用户
    @PostMapping
    public Result<Boolean> addUser(@RequestBody User user) {
        return Result.ok(userService.save(user));
    }

    // 4. 更新用户
    @PutMapping
    public Result<Boolean> updateUser(@RequestBody User user) {
        return Result.ok(userService.updateById(user));
    }

    // 5. 删除用户
    @DeleteMapping("/{id}")
    public Result<Boolean> deleteUser(@PathVariable Long id) {
        return Result.ok(userService.removeById(id));
    }

    // 6. 条件查询（示例：查询年龄大于18的用户）
    @GetMapping("/adults")
    public Result<List<User>> getAdults() {
        QueryWrapper<User> queryWrapper = new QueryWrapper<>();
        queryWrapper.gt("age", 18);
        return Result.ok(userService.list(queryWrapper));
    }
}